﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Entities;
using System.Data.Linq;

namespace DataAccess.Repositories
{
    public class EventRepository : IEventRepository
    {
        private readonly IntecDataContext _db = new IntecDataContext();
        private readonly Table<Event> _eventsTable;

        public EventRepository()
        {
            _eventsTable = _db.GetTable<Event>();
        }

        #region IEventRepository Members

        public Event FetchByID(Guid id)
        {
            return (from e in _eventsTable
                    where e.EventID == id
                    select e).First();
        }

        public IEnumerable<Event> FetchAll()
        {
            return _eventsTable.AsEnumerable<Event>();
        }

        public IEnumerable<Event> FetchLastEvents(int amount)
        {
            IEnumerable<Event> allEvents = this.FetchAll();

            if (allEvents != null && amount > 0)
                return allEvents.Count() <= amount ? allEvents.OrderByDescending(e => e.Date) :
                    allEvents.OrderByDescending(e => e.Date).Take(amount);
            else
                return null;
        }

        public void InsertOnSubmit(Event e)
        {
            _eventsTable.InsertOnSubmit(e);
        }

        public void InsertOnSubmit(string title, string description, string place, DateTime date)
        {
            InsertOnSubmit(new Event(title, description, place, date));
        }

        public void UpdateOnSubmit(Event e)
        {
            return;
        }

        public void DeleteOnSubmit(Event e)
        {
            _eventsTable.DeleteOnSubmit(e);
        }

        public void SubmitChanges()
        {
            _db.SubmitChanges();
        }

        #endregion
    }
}
